{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "from pycocotools.coco import COCO\n",
    "from pycocotools import mask as cocomask\n",
    "import numpy as np\n",
    "import cv2\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "\n",
    "def generate_masks(src_annotations, target_image_path):\n",
    "    coco = COCO(src_annotations)\n",
    "    # category_ids = coco.loadCats(coco.getCatIds())\n",
    "    # print(category_ids)\n",
    "\n",
    "    # This generates a list of all `image_ids` available in the dataset\n",
    "    image_ids = coco.getImgIds(catIds=coco.getCatIds())\n",
    "\n",
    "    count = 0\n",
    "    for image_id in image_ids:\n",
    "        img = coco.loadImgs(image_id)[0]\n",
    "        annotation_ids = coco.getAnnIds(imgIds=img['id'])\n",
    "        annotations = coco.loadAnns(annotation_ids)\n",
    "\n",
    "        # 一个图会有多个annotation对象\n",
    "        mask = np.zeros([300, 300])  # 这里所有图像都是300*300\n",
    "        for _idx, annotation in enumerate(annotations):\n",
    "            rle = cocomask.frPyObjects(annotation['segmentation'], img['height'], img['width'])\n",
    "            m = cocomask.decode(rle)  # (300, 300, 1)\n",
    "            m = m.reshape((img['height'], img['width']))\n",
    "            # 全是0和1的图片，执行OR运算求并集\n",
    "            mask = np.logical_or(mask, m)\n",
    "\n",
    "        filename = target_image_path + '{:012d}'.format(image_id) + '.jpg'\n",
    "        cv2.imwrite(filename, mask * 255)\n",
    "\n",
    "        if count % 10000 == 0:\n",
    "            print(\"handled %s images\" % (count, ))\n",
    "        count += 1\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 修改数据路径\n",
    "data_directory = \"/home/shenshen/Programs/mc_data/\"\n",
    "annotation_file_template = \"{}/{}/annotation{}.json\"\n",
    "\n",
    "TRAIN_IMAGES_DIRECTORY = \"train/images/\"\n",
    "TRAIN_ANNOTATIONS_PATH = \"train/annotation.json\"\n",
    "TRAIN_ANNOTATIONS_SMALL_PATH = \"train/annotation-small.json\"\n",
    "MASK_IMG_SAVE_PATH = \"train/masks/\"\n",
    "\n",
    "VAL_IMAGES_DIRECTORY = \"val/images/\"\n",
    "VAL_ANNOTATIONS_PATH = \"val/annotation.json\"\n",
    "VAL_ANNOTATIONS_SMALL_PATH = \"val/annotation-small.json\"\n",
    "VAL_MASK_IMG_SAVE_PATH = \"val/masks/\"\n",
    "\n",
    "print('generating train masks......')\n",
    "generate_masks(data_directory + TRAIN_ANNOTATIONS_PATH, data_directory + MASK_IMG_SAVE_PATH)\n",
    "print('generating val masks......')\n",
    "generate_masks(data_directory + VAL_ANNOTATIONS_PATH, data_directory + VAL_MASK_IMG_SAVE_PATH)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
